#include "daemon_sub_process.h"
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/reboot.h>
#include <signal.h>
/**
 * @brief 初始化子进程
 */
sub_process_t *daemon_sub_process_init(char *cmd)
{
    sub_process_t *sub_process = (sub_process_t *)malloc(sizeof(sub_process_t));
    sub_process->cmd = cmd;
    sub_process->pid = -1;
    sub_process->failed_count = 0;

    return sub_process;
}

/**
 * @brief 检查or启动子进程
 */
int  daemon_sub_process_check_and_start(sub_process_t *sub_process)
{
    int  over_status = 0;
    // 检查  
    if(sub_process->pid ==-1  //没启动过
        ||  waitpid(sub_process->pid,&over_status,WNOHANG) ==-1 //子进程挂掉
        )
    {
      //需要启动的
      //对异常结束进行计数 ，超过阈值重启
      if(over_status!=0 )
      {
        sub_process->failed_count++;
        if(sub_process->failed_count>MAX_FAILED_COUNT) 
        {
           reboot(RB_AUTOBOOT);
        } 
      }
      // 启动程序  fork+execve 
      sub_process->pid = fork();
      if(sub_process->pid ==0)
      {
        //子进程
        char *proc="/usr/bin/gateway";
        char *args[]={"/usr/bin/gateway",sub_process->cmd,NULL};
        char *env[]={ NULL};
        int ret= execve(proc,args,env);
         if(ret==-1)
         {
           perror("子进程启动失败\n");
           _exit(EXIT_FAILURE);
         }
      }
    }
    return 0;
}

/**
 * @brief 销毁子进程
 */
void daemon_sub_process_destroy(sub_process_t *sub_process)
{
    if(sub_process)
    {
        if(sub_process->pid>0)
        {
            kill(sub_process->pid,SIGTERM);
            waitpid(sub_process->pid,NULL,0);
        }

        free(sub_process);
    }
}